import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import {AIChatRequest} from './AIChatRequest';

@Injectable({
  providedIn: 'root'
})
export class AiService {
  private socket?: WebSocket;
  constructor() { }
  streamChat(request: AIChatRequest): Observable<string> {
    return new Observable<string>((observer) => {
      const wsUrl = environment.apiUrl.replace(/^http/, 'ws') + '/ai/stream-chat';

      this.socket = new WebSocket(wsUrl);

      this.socket.onopen = () => {
        console.log('[WebSocket] connected');
        this.socket?.send(JSON.stringify(request));
      };

      this.socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.success) {
          if (data.content) {
            observer.next(data.content); // 推送每一段内容
          }
          if (data.done) {
            observer.complete(); // 完成
          }
        } else {
          observer.error(data.error || 'Unknown error from AI backend');
        }
      };

      this.socket.onerror = (error) => {
        console.error('[WebSocket] error:', error);
        observer.error('WebSocket error');
      };

      this.socket.onclose = (event) => {
        console.log('[WebSocket] closed:', event);
      };

      // 提供取消订阅时关闭连接
      return () => {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          this.socket.close();
        }
      };
    });
  }
}
